/* eslint-disable no-plusplus */
import React, { useState, useEffect } from 'react';
import {
  TextField, Button, Icon, message,
} from 'choerodon-ui/pro';
import { axios } from '@choerodon/master';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import { handleCopyOk } from '@/routes/continuous-deployment/utils';
import './index.less';

const prefixCls = 'c7ncd-continuous-deployment-tokenPopover';

export const PopoverHeader = () => (
  <div className={`${prefixCls}-header`}>
    个人令牌
    <div id="triangle" />
    <div className="line" />
  </div>
);

export interface IProps {
  personalToken: string
  handleTokenReset: (t:string)=> void,
  projectId:string,
}

const PopoverContent = (props:IProps) => {
  const { personalToken, handleTokenReset, projectId } = props;

  const [placeholderValue, setPlaceholderValue] = useState('');
  const [showInputValue, setShowInputValue] = useState(false);
  const [token, setToken] = useState('');

  useEffect(() => {
    setToken(personalToken);
  }, [personalToken]);

  useEffect(() => {
    let attr = '';
    for (let i = 0; i < token.length; i++) {
      attr += '*';
    }
    setPlaceholderValue(attr);
  }, [token]);

  const handleChangeInputValue = () => {
    setShowInputValue(!showInputValue);
  };

  const handleResetToken = async () => {
    const res = await axios.put(`/devops/v1/projects/${projectId}/pipelines/personal_token/reset`);
    message.success('重置令牌成功');
    setToken(res);
    handleTokenReset(res);
  };

  return (
    <div className={prefixCls}>
      <main className={`${prefixCls}-content`}>
        <TextField value={showInputValue ? token : placeholderValue} disabled />
        <CopyToClipboard
          text={token}
          onCopy={handleCopyOk}
        >
          <div className="btn-copy" role="button">复制令牌</div>
        </CopyToClipboard>
        {
          !showInputValue && <Icon type="visibility-o" onClick={() => { handleChangeInputValue(); }} />
        }
        {
          showInputValue && <Icon type="visibility_off-o" onClick={() => { handleChangeInputValue(); }} />
        }
        <div className="line" />
      </main>
      <footer>
        <Button onClick={handleResetToken}>重置</Button>
      </footer>
    </div>
  );
};

export default PopoverContent;
